﻿@page "/permissions/index"
@attribute [Authorize(Policy = nameof(ApiRoutes.Permission.QueryPermissions))]

@inject ExampleJsInterop JsInterop
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject IAuthorizationService AuthorizationService
@inject DialogService DialogService
@inject IPermissionService PermissionService

<RadzenCard Variant="Variant.Filled" Style="height : 100%;">
    <RadzenSplitter Orientation="Orientation.Vertical" style="height:100%;">
        <RadzenSplitterPane Size="100px">
            <RadzenSplitter>
                <RadzenSplitterPane Size="20%" Min="20%" Max="30%">
                    <RadzenTree Data=@TreeData Change=@ChangeHandler @bind-Value=_selectionTreeData Style="height: 100%;width:100%">
                        <RadzenTreeLevel TextProperty="Name" ChildrenProperty="Children"
                                         HasChildren=@(e => (e as PermissionTreeResponseDto)?.Children?.Any()??false) />
                    </RadzenTree>
                </RadzenSplitterPane>
                <RadzenSplitterPane>
                    <RadzenStack class="rz-m-2">
                         <SearchFormPartial Model="_searchRequestDto" QueryHandler="QueryHandler"></SearchFormPartial>
                        
                        <SearchTablePartial @ref="_requestTable" T="PermissionInfoResponseDto" ServerData="ServerReload"
                                            SearchPartial="_searchPartial"
                                            AddHandler="AddHandler" EditHandler="EditHandler">
                        </SearchTablePartial>
                    </RadzenStack>
                </RadzenSplitterPane>
            </RadzenSplitter>
        </RadzenSplitterPane>
    </RadzenSplitter>
</RadzenCard>


@code {

    private IEnumerable<PermissionInfoResponseDto> _pagedData = new List<PermissionInfoResponseDto>();
    private SearchPartialInfo _searchPartial = new();
    private SearchTablePartial<PermissionInfoResponseDto> _requestTable = new();
    private int _totalItems;
    private PermissionSearchRequestDto _searchRequestDto = new();
    
    protected IList<PermissionTreeResponseDto> TreeData = new List<PermissionTreeResponseDto>();
    private object _selectionTreeData = null;


    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();

        var authenticationState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        _searchPartial.IsAdd = (await AuthorizationService.AuthorizeAsync(authenticationState.User, nameof(ApiRoutes.Permission.CreatePermission))).Succeeded;
        _searchPartial.IsEdit = (await AuthorizationService.AuthorizeAsync(authenticationState.User, nameof(ApiRoutes.Permission.UpdatePermission))).Succeeded;
        _searchPartial.IsDelete = (await AuthorizationService.AuthorizeAsync(authenticationState.User, nameof(ApiRoutes.Permission.DeletePermission))).Succeeded;
        _searchPartial.IsImportExcel = (await AuthorizationService.AuthorizeAsync(authenticationState.User, nameof(ApiRoutes.Permission.ImportPermission))).Succeeded;
        _searchPartial.IsExportExcel = (await AuthorizationService.AuthorizeAsync(authenticationState.User, nameof(ApiRoutes.Permission.ExportPermission))).Succeeded;

        await LoadTreeServerData();
    }

    async Task LoadTreeServerData()
    {
        var result = await PermissionService.QueryPermissionsByTree(1);
        if (result.Succeeded)
        {
            TreeData = result.Data;
        }
    }

    async Task QueryHandler(MouseEventArgs args)
    {
        await _requestTable.ReloadServerData();
    }

    async Task ChangeHandler()
    {
        await _requestTable.ReloadServerData();
    }

    async Task AddHandler(MouseEventArgs args)
    {
        await DialogService.OpenAsync<PermissionEdit>("Add Permission", null);
        await _requestTable.ReloadServerData();
    }

    async Task EditHandler(MouseEventArgs args, PermissionInfoResponseDto context)
    {
        await DialogService.OpenAsync<PermissionEdit>("Edit Permission", new Dictionary<string, object> { { "Key", context.Key } });
        await _requestTable.ReloadServerData();
    }


    /// <summary>
    /// Here we simulate getting the paged, filtered and ordered data from the server
    /// </summary>
    private async Task<ODataServiceResult<PermissionInfoResponseDto>> ServerReload(LoadDataArgs state)
    {
        if (_selectionTreeData != null)
        {
            var permissionTreeResponseDto = (PermissionTreeResponseDto)_selectionTreeData;
            if (permissionTreeResponseDto.Key != Guid.Empty)
            {
                _searchRequestDto.ParentId = permissionTreeResponseDto.Key;
            }
        }

        if (state.Skip != null) _searchRequestDto.Page = (int)(state.Skip + 1);
        if (state.Top != null) _searchRequestDto.Limit = (int)state.Top;
        var data = await PermissionService.QueryPermissions(_searchRequestDto);

        if (data != null)
        {
            _pagedData = data.Data;
            _totalItems = data.TotalCount;
        }

        return new ODataServiceResult<PermissionInfoResponseDto>() { Count = _totalItems, Value = _pagedData };
    }

}